define([
    'Util',
    'list',
    'dialog',
    'text!tpl/sprint/viewSprint.tpl',
    'text!tpl/sprint/tab.tpl',
    'tab',
    'cookie',
    '../common/getPath',
    'form',
    'loading',
    '../requirement/fileList',
    '../common/dateFormat'
], function(Util, List, Dialog, vSprints, tabletpl, Tab, $cookie, AjaxPath, Form, Loading, fileList) {
    require(['style!css/style.css']);
    var $el=null,
        $tabel = null;
    var _indexModule = null,
        list = null,
        tab = null,
        tplId = null,
        useMode = null,
       // projectJsonData = null,        //记录当前页面选择的是51，9，还是4
        sprintTabData = null,
        sprintTable = null,
        handLoading = null,
        sprintReqList = null,
        loadingConfig = null,
        viewSprintTable = null,
        activeData = null;
    var initialize = function(indexModule, options, tabItem){
        $el = $(vSprints);
        $tabel = $(tabletpl);
        _indexModule = indexModule;
        $(tabItem).on("tabActive", function() {
            tabItem.show(true); // 刷新表单
        });
        tab = tabItem;
        this.content=$el;
        tplId = options.menuId;
        sprintTabData = options;
        // 业务相关代码
        createLoading();
        tables();
        listInit();
        eventInit();
        activeRecordInit();
        getAuthority($el); 

    };
    //按钮点击
    var eventInit = function (){
        //页面除dialog按钮功能
        $el.on('click', '.btnBack', back);
        $el.on('click', '.sliderContainer .tri', bindTableSwitch)//折叠
        $el.on('click', '#shiftOutSprint', moveOutSprint);//批量移出
        $el.on('click', '.moveSprint', moveOutSprint);//移出
        $el.on('click', '.sprint-tab li', activeRecordInitTab);//tab切换
     };

    var back = function() {
        tab.switchTab(sprintTabData.menuId);
        tab.destroy('viewSprintTab');
        $(".ui-popup-backdrop, .ui-popup,.ui-popup-modal,.ui-popup-show,.ui-popup-focus").remove();
    }
    
    //折叠
    var bindTableSwitch = function(e){
        $(this).toggleClass('tri-left');
        $(this).parent('.t-list-title').siblings().stop().slideToggle();
    }
   
    //table
    var tables = function(e){
        var obj = {};
        Util.ajax.getJson(AjaxPath.project+"/sprints/" + sprintTabData.id, {}, function(result, isok) {
            var item=result.beans.sprint;
                item.startTime = new Date(item.startTime).Format('yyyy-MM-dd');
                item.endTime = new Date(item.endTime).Format('yyyy-MM-dd');
           // item.linkClassName = "viewLinkClassName";
            $(".sprintTab", $el).html(Util.hdb.compile(tabletpl)(item));
             if(item.isDefault === 1){
                    $("#shiftOutSprint",$el).attr('disabled',true).css({'cursor':'default'}).removeClass('t-btn-white').addClass('t-btn-grey');
                }
            
        });
    }
           
    
   
    //迭代内的需求
    var listInit = function (e){
        viewSprintTable = new List({
            el: $('.sprintTableCnt', $el),
            ajax:{    //所有jquery.ajax的配置项均可配置，这些配置将替换底层组件的配置；慎用
                method:'GET'
            },
            field: {
                boxType: 'checkbox',
                key: 'id',
                items: [
                    {
                        //sorting:1,
                        text: '需求名称',
                        title: 'requireTitle',
                        name: 'requireTitle',
                        className: 'w90',
                        width:150,
                        click: function (e, val, item) {

                            checkSprint(e, item);

                        },
                        render: function (item, val) {
                            return '<a href="javascript:;" class="text-overflow" style="line-height:36px;display:block;outline:none">' + val + '</a>';
                        }
                    },
                    {
                        text: '需求编号',
                        title: 'requireNum',
                        name: 'requireNum',
                        className: 'w90',
                        //sorting:1,
                        width:150,
                        click: function (e, val, item) {

                            checkSprint(e, item);

                        },
                        render: function (item, val) {
                            return '<a href="javascript:;" class="text-overflow" style="line-height:36px;display:block;outline:none">' + val + '</a>';
                        }
                    },
                    {
                        text: '提出日期',
                        title: 'proposeTime',
                        name: 'proposeTime',
                        className: 'w90',
                        //sorting:1,
                        width:150
                    },
                    {
                        text: '创建时间',
                        title: 'createTime',
                        name: 'createTime',
                        className: 'w90',
                        //sorting:1,
                        width:150,
                        render: function (item, val) {
                            return new Date(val).Format("yyyy-MM-dd hh:mm:ss");
                        }
                    },
                    {
                        text: '更新时间',
                        title: 'updateTime',
                        name: 'updateTime',
                        className: 'w90',
                        //sorting:1,
                        width:150,
                        render: function (item, val) {
                            return new Date(val).Format("yyyy-MM-dd hh:mm:ss");
                        }

                    },
                    {
                        text: '状态',
                        title: 'statusName',
                        name: 'statusName',
                        className: 'w90',
                        //sorting:1,
                        width:130
                       
                    },
                    {
                        text: '需求类型',
                        title: 'requireType',
                        name: 'requireType',
                        className: 'w90',
                        width:130,
                        // //sorting:1
                    },
                    {
                        text: '经办人',
                        title: 'tryPeopleName',
                        name: 'tryPeopleName',
                        className: 'w90',
                        width:150,
                        // //sorting:1
                    },
                    {
                        text: '提出人',
                        title: 'presentPeople',
                        name: 'presentPeople',
                        className: 'w90',
                        width:150,
                        // //sorting:1
                    },
                    {
                        text: '操作',
                        title: '',
                        name: '',
                        width:130,
                        className: 'w90',
                        click: function (e, val, item) {
                            // console.log(val,item);
                        },
                        render: function (item, val) {
                            var defaultButton = "",
                                background='#63a8eb';
                            if(sprintTabData.isDefault === 1){
                                defaultButton = "disabled";
                                background="#808a94";
                            }

                            return '<button style="margin-right:2px;background: '+background+'" '+defaultButton+' class="t-btn t-btn-blue t-btn-xs moveSprint"><a style="color:#fff">移出迭代</a></button>';
                        }
                       
                    }]
            },
            page: {
                customPages: [2, 3, 5, 6, 10, 15, 20, 30, 50], //可选择每页显示多少条
                perPage: 5, //默认每页显示多少条记录
                total: true
            },
            data: {//'/requires?sprintId=&systemId='+ sprintTabData.systemId + '?type=1'
                url: AjaxPath.demand + "/requires?sprintId="+ sprintTabData.id + "&systemId=" + $cookie.get("projectSelectId")+ "&type=1&userId=" + $cookie.get("userId")
            }
        });
        viewSprintTable.search();
    };


    //移出迭代
    var moveOutSprint = function(e){
        
        if(e.currentTarget.id!=="shiftOutSprint"){
            $(".sprintTableCnt .sn-list-content-locker.sn-list-show table tbody tr.selected td",$el).click();
            $(".sprintTableCnt .sn-list-show table tbody tr",$el).eq(e.currentTarget.parentNode.parentNode.rowIndex).find('td').click();
        }

        handLoading = new Loading(loadingConfig);
        var nodes = viewSprintTable.getCheckedRows();
        console.log(nodes.length);
        if(nodes.length < 1) {
            handLoading.destroy();
            config = {
                mode: 'tips',
                content: '<div style="text-align:center;margin-top:70px">请选择至少一条数据进行操作！</div>',
                width: 300, //对话框宽度，可选项。normal默认值为600，confirm默认值为300，tips默认值为240
                height: 150, //对话框高度，可选项。normal默认值为400，confirm默认值为180，tips默认值为80
                cancelDisplay: false
            };
            var dialog = new Dialog(config);
        } else {
            var data = [];
            for(var i = 0; i < nodes.length; i++) {
                data.push(viewSprintTable.getCheckedRows()[i].id);
            }
           
            var str = JSON.stringify(data);
            moveSprint(nodes, data, str);
        }    
    }
    var moveSprint = function(nodes, data, str) {
        handLoading.destroy();
        var urlId = $cookie.get("projectSelectId");
        console.log(urlId);
        var config = {
            mode: 'confirm', //对话框模式，默认normal标准|tips浮动层|confirm确认对话框
            title: "移出提示", //对话框标题
            content: '<div style="text-align:center;margin-top:50px">确认移出选择的需求？</div>' /* + content.substring(0,content.length-1)*/ , //对话框内容，可以是字符串、html片段、或dom对象,默认为loading状态（点组成的圈）
            ok: function() {
                handLoading = new Loading(loadingConfig);
                moveOutViewSprint(nodes, data, urlId);
                return true;
            }, // 配置该项时才会出现ok按钮，回调函数可为空。如果指定 return false 则执行完方法后不关闭对话框。默认 return true
            okValue: '确定', //确定按钮的文本 默认是 ‘ok’
            cancel: function() {}, //取消按钮的回调函数,配置该项时才会出现关闭按钮，回调函数可为空。
            cancelValue: '取消', //取消按钮的文本 默认是 ‘关闭’
            cancelDisplay: true, //是否显示取消按钮 默认true显示|false不显示
            width: 300, //对话框宽度，normal默认值为600，confirm默认值为300，tips默认值为240
            height: 120, //对话框高度，normal默认值为400，confirm默认值为180，tips默认值为80
            padding: '0 16px 1em 10px', //(默认值: 继承 css 文件设置) 设置消息内容与消息容器的填充边距，即 style padding属性
            align: 'bottom right', //设置对话框与其他元素的对齐方式。仅在show(elem)与showModal(elem)传入元素时生效。默认值: "bottom left"。可选："top left" "top" "top right" "right top" "right" "right bottom" "bottom right" "bottom" "bottom left" "left bottom" "left" "left top"。
            skin: 'dialogSkin dialogSkin2', //设置对话框额外的className参数,多个className请使用空格隔开。
            fixed: true, //是否开启固定定位 默认false不开启|true开启
            quickClose: false, //点击空白处快速关闭 默认false不关闭|true关闭
            modal: true, //是否开启模态框状态  默认false不开启|true开启,confirm默认状态为true
            beforeOpen: function() {}, //对话框打开之前执行。
            zIndex: 990 // 对话框的z-index值，默认是1024。
        };
        var delDialog = new Dialog(config)
    };

    var moveOutViewSprint = function(nodes, data, urlId) {
        
        if(nodes.length===1){
            Util.ajax.getJson(AjaxPath.project+ "/sprints/removeRequire/" + nodes[0].id +"/"+ urlId +"/"+ $cookie.get('userId'), {}, function(result, isok) {
                
            if(result.returnCode === '0000'){
                 var flag = result.returnMessage;
                if(undefined === flag) {
                    handLoading.destroy();
                    new Dialog({
                        mode: 'tips',
                        content: '<div style="text-align:center;margin-top:70px">移出成功！</div>',
                        width: 300, //对话框宽度，可选项。normal默认值为600，confirm默认值为300，tips默认值为240
                        height: 150, //对话框高度，可选项。normal默认值为400，confirm默认值为180，tips默认值为80
                        cancelDisplay: false
                    });
                } else {
                    handLoading.destroy();
                    new Dialog({
                        mode: 'tips',
                        content: '<div style="text-align:center;margin-top:70px">'+ result.returnMessage +'</div>',
                        width: 300, //对话框宽度，可选项。normal默认值为600，confirm默认值为300，tips默认值为240
                        height: 150, //对话框高度，可选项。normal默认值为400，confirm默认值为180，tips默认值为80
                        cancelDisplay: false
                    });
                    
                       
                }
                 viewSprintTable.search();
            }
               
            })
        } else {
            Util.ajax.postJson(AjaxPath.project+ "/sprints/batchRemoveRequire/" + urlId +"/"+ $cookie.get('userId'), JSON.stringify(data),  function(result, isok) {
                var flag = result.returnMessage;
                if(result.returnCode === '0000'){
                    var flag = result.returnMessage;
                    if(undefined === flag) {
                        handLoading.destroy();
                        new Dialog({
                            mode: 'tips',
                            content: '<div style="text-align:center;margin-top:70px">批量移出成功！</div>',
                            width: 300, //对话框宽度，可选项。normal默认值为600，confirm默认值为300，tips默认值为240
                            height: 150, //对话框高度，可选项。normal默认值为400，confirm默认值为180，tips默认值为80
                            cancelDisplay: false
                        });
                    } else {
                        handLoading.destroy();
                        new Dialog({
                            mode: 'tips',
                            content: '<div style="text-align:center;margin-top:70px">'+ result.returnMessage +'</div>',
                            width: 300, //对话框宽度，可选项。normal默认值为600，confirm默认值为300，tips默认值为240
                            height: 150, //对话框高度，可选项。normal默认值为400，confirm默认值为180，tips默认值为80
                            cancelDisplay: false
                        });
                    
                       
                }
                 viewSprintTable.search();
              }
            })
        }        
    }
   


    //查看工作项
    var checkSprint= function(e, data){
        var viewSprintTable = data.data;
            viewSprintTable.menuId = tplId;

        tab.createTab({
            title: '查看工作项',
            closeable: 1, //是否可以关闭 0false不可以|1true可以
            className: 'viewSprintTab'
        });
        tab.switchTab('查看工作项');
        require(['js/requirement/viewRequirement'], function(viewSprintContent) {
            var result = new viewSprintContent({}, viewSprintTable, tab);
            tab.content(result.content);
        });

        $(".ui-popup-backdrop, .ui-popup,.ui-popup-modal,.ui-popup-show,.ui-popup-focus").remove();
   
        
    }

   
   
    //活动日志
    //
    var switchTab = function(index) {
        $(".t-tabs-items li", $el).eq(index).trigger('click');
    }

    var bindTableSwitch = function(e){
        $(this).toggleClass('tri-left');
        $(this).parent('.t-list-title').siblings().stop().slideToggle();
    };
    var search = function(pageIndex) {
        var data = {};
        data.useMode = $(".sprint-tab li.actived").attr("data");
        list.search(data,pageIndex ? pageIndex : "");
    };
    
    var activeRecordInit = function(){
        var config = {
            el: $('.activeRecordContainer', $el),
            ajax:{    //所有jquery.ajax的配置项均可配置，这些配置将替换底层组件的配置；慎用
                method:'GET'
            },
            field: {
               /* boxType: 'checkbox',*/
                key: 'id',
                items: [
                    {
                        text: '经办人',
                        name: 'createrName',
                        className: 'w90',
                        width:100
                    },
                    {
                        text: '记录',
                        name: '',
                        className: 'w50 text-break',
                        width:400,
                        render: function (item, val) {
                            return '<p class="fn-left">于&nbsp;&nbsp;' + new Date(item.createTime).Format('yyyy-MM-dd hh:mm:ss') +(item.refContent==null?'':('&nbsp;&nbsp;将需求：<a>'+item.refContent)+'</a>,')+'&nbsp;&nbsp;'+item.typeName + '了 ' + item.businessType  + ': <a href="javascript:;" data="'+ item.businessId +'" class="viewSubTaskBtn">'+ item.businessTitle +'</a>' + item.content +'。</p>';
                        }
                       

                    }]
            },
            page: {
                customPages: [2, 3, 5, 6, 10, 15, 20, 30, 50], //可选择每页显示多少条
                perPage: 5, //默认每页显示多少条记录
                total: true
            },
            data: {
                url:AjaxPath.project + '/logInfo/query?businessId='+ sprintTabData.id +'&businessType=sprint'
                // url:"http://192.168.91.172:8089/devops-project/projects"
                //url:"../../../data/list1.json"
            }
        };
        
        list = new List(config);
        list.search();
        $("#oTabel" ,$el).find(".sn-list-header-wrap").hide();
    };

    var activeRecordInitTab = function(e){                                                                                                              
        var data={};
        $(this).addClass('actived').siblings().removeClass('actived');
        data.type = $(this).attr("data");
        list.search(data);
    };
   
    //验证权限
    var getAuthority = function($el) {
        Util.ajax.getJson(AjaxPath.auth + '/authority/button/'+ $cookie.get("userId") +'?datas=[{"mo":"29","btnId":""}]', {}, function(result, json){
            if(result.returnCode==="0000"){
                if(result.beans[0].mo===0){
                    Authority = false;
                }else {
                    Authority = true;
                }
                listInit();
            }
        });
        require(['js/btnAuthority'], function(Authority){
            new Authority($el);
        }); 
    }
    

   var createLoading = function() {
            loadingConfig = {
                el: 'body', //组件要绑定的容器，默认为body（此项可不配置或留空）
                className: 'loading', //组件外围的className
                position: 'center', //提示信息位置，顶部top|默认center中央
                width: '300', //loading的宽度,非必须，默认300
                height: 'auto', //loading的宽度,非必须，默认auto
                mask: 1, //是否显示遮罩， 0不显示|默认1显示
                animate: 1, //是否显示动画效果， 0不显示|默认1显示
                mode: 'layer', //展示方式 loadingLine线条方式|默认layer弹层方式
                text: '加载中...', //提示文字，默认 加载中...
                icon: 'dotCycle', //文字前面的gif动画， 默认dotCycle有点组成的圈|cmcc移动图标|cmccLarge大的移动图标
            }
        };

    return initialize;
});